package com.haojie.server;

import com.haojie.common.RPCRequest;
import com.haojie.common.RPCResponse;
import lombok.AllArgsConstructor;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

@AllArgsConstructor
public class WorkThread implements Runnable {
    private Socket socket;
    private ServiceProvider serviceProvider;

    @Override
    public void run() {
        try {
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            RPCRequest request = (RPCRequest) in.readObject();
            RPCResponse response = getResponse(request);

            out.writeObject(response);
            out.flush();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    private RPCResponse getResponse(RPCRequest request) {

        String interfaceName = request.getInterfaceName();
        Object service = serviceProvider.getService(interfaceName);
        try {

            String methodName = request.getMethodName();
            Class<?>[] paramsTypes = request.getParamsType();
            Method method = service.getClass().getMethod(methodName, paramsTypes);

            Object invoke = method.invoke(service, request.getParams());
            return RPCResponse.success(invoke);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("方法执行错误");
            return RPCResponse.fail();
        }

    }
}
